﻿using System;
using WeDonekRpc.Client;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper.Config;
using WeDonekRpc.HttpApiGateway.Interface;
using WeDonekRpc.HttpApiGateway.Model;
namespace WeDonekRpc.HttpApiGateway.Config
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class HttpConfig : IHttpConfig
    {
        private static IHttpConfig _Cur;
        private static Action<IHttpConfig, string> _refreshEvent;
        public HttpConfig ()
        {
            _Cur = this;
            this.UpConfig = new UpConfig();
            RpcClient.Config.GetSection("gateway:http:server").AddRefreshEvent(this._RefreshHttp);
        }
        private void _RefreshHttp (IConfigSection config, string name)
        {
            this.Url = config.GetValue<Uri>("Url");
            this.RealRequestUri = config.GetValue<Uri>("RealRequestUri");
            this.MaxRequstLength = config.GetValue<long>("MaxRequstLength");
            this.ApiRouteFormat = config.GetValue<string>("ApiRouteFormat", "/api/{controller}/{name}");
            if (this.RealRequestUri == null)
            {
                this.RealRequestUri = this.Url;
            }
            if (name != string.Empty)
            {
                _refreshEvent?.Invoke(_Cur, name);
            }
        }

        public bool CheckContentLen (long len)
        {
            return this.MaxRequstLength == 0 || len < this.MaxRequstLength;
        }

        public void RefreshEvent (Action<IHttpConfig, string> action)
        {
            _refreshEvent += action;
        }

        /// <summary>
        /// Api响应模板
        /// </summary>
        public IApiResponseTemplate ApiTemplate
        {
            get;
            set;
        } = new Response.ApiResponseTemplate();
        /// <summary>
        /// 网关地址
        /// </summary>
        public Uri Url { get; private set; }

        public string ApiRouteFormat { get; private set; }
        /// <summary>
        /// 最大请求长度
        /// </summary>
        public long MaxRequstLength { get; private set; }

        public UpConfig UpConfig { get; private set; }

        public Uri RealRequestUri { get; private set; }
    }
}
